import React from 'react'
import { NavBar, Icon, Toast } from 'antd-mobile'
import axios from 'axios'
import {getCity} from '../../utils/index'
import {List, AutoSizer} from 'react-virtualized'
import './index.scss'

export default class Citylist extends React.Component {
  listComponent = React.createRef()

  firstCity = ['北京', '上海', '广州', '深圳']

  state = {
    cityIndex: [],
    cityList: {},
    activeIndex: 0
  }

  cityItem = {
    titleHeight: 36,
    nameHeight: 50
  }

  formatCity(list) {
    const cityList = {}
    

    list.forEach(item => {
      const key = item.pinyin.substring(0, 1)
      if(cityList[key]) {
        cityList[key].push(item)
      } else {
        cityList[key] = [item]
      }
    })
    const cityIndex = Object.keys(cityList).sort()

    return {
      cityList,
      cityIndex
    }
  }

  async getCityList() {
    const {data} = await axios.get('http://127.0.0.1:8080/area/city', {
      params: { level: 1}
    })

    const { cityList, cityIndex } = this.formatCity(data.body)

    const {data: hotData} = await axios.get('http://127.0.0.1:8080/area/hot')

    cityList['hot'] = hotData.body
    cityIndex.unshift('hot')

    const localCity = await getCity()
    cityList['#'] = [localCity]
    cityIndex.unshift('#')

    this.setState({
      cityIndex,
      cityList
    })
  }

  async componentDidMount() {
    await this.getCityList()

    this.listComponent.current.measureAllRows()
  }

  renderNavBar() {
    return (
      <NavBar
        mode="light"
        icon={<Icon type="left" size="md" />}
        onLeftClick={() => this.props.history.go(-1)}
      >
        城市列表
      </NavBar>
    )
  }

  formatTitle = (title) => {
    switch(title) {
      case '#':
        return '当前定位'
      case 'hot':
        return '热门城市'
      default:
        return title.toUpperCase() 
    }
  }

  changeCity = (info) => {
    if(this.firstCity.includes(info.label)) {
      localStorage.setItem('hkzf_city', JSON.stringify(info))
      this.props.history.go(-1)
    } else {
      Toast.info('您要切换的城市失败', 2, null, false)
    }
  }

  rowCityItemRender = ({
    key,
    index, 
    isScrolling,
    isVisible,
    style
  }) => {
    const title = this.state.cityIndex[index]
    return (
      <div key={key} style={style} className="cityitem-box">
        <div className="title">{this.formatTitle(title)}</div>
        {this.state.cityList[title].map(item => {
          return (<div className="name" onClick={()=>this.changeCity(item)} key={item.value}>{item.label}</div>)
        })}
      </div>
    )
  }
  
  rowHeightItem = ({index}) => {
    const key = this.state.cityIndex[index]
    return this.cityItem.titleHeight + this.cityItem.nameHeight * this.state.cityList[key].length
  }

  onRowsRendered = ({ startIndex }) => {
    if(startIndex !== this.state.activeIndex) {
      this.setState({
        activeIndex: startIndex
      })
    }
  }

  renderCityList() {
    return (
      <AutoSizer>
        {({height, width}) => (
          <List
            ref={this.listComponent}
            width={width}
            height={height}
            rowCount={this.state.cityIndex.length}
            rowHeight={this.rowHeightItem}
            rowRenderer={this.rowCityItemRender}
            onRowsRendered={this.onRowsRendered}
            scrollToAlignment="start"
          />
        )}
      </AutoSizer>
    )
  }

  renderCityIndex() {
    return (
      <ul className="city-index">
        {
          this.state.cityIndex.map((item,index) => {
            return (
              <li className="city-index-item" key={item} onClick={()=>{console.log(this.listComponent.current.scrollToRow(index))}}>
                <span className={this.state.activeIndex === index? 'index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
              </li>
            )
          })
        }  
      </ul>
    )
  }

  render() {
    return (
      <div className="citylist-box">
        {/* 顶部导航 */}
        {this.renderNavBar()}

        {/* 城市信息 */}
        {this.renderCityList()}

        {/* 索引渲染 */}
        {this.renderCityIndex()}
      </div>
    )
  }
}